<template>
  <div class="app-container">
    <top-steps
      :state-steps="stateSteps"
      :active-state="activeState"
      @changeState="changeState"
    />
    <div class="topSearch">
      <el-row>
        <el-input
          v-model="searchCriteria.name"
          maxlength="50"
          clearable
          placeholder="title"
        />
        <el-input
          v-model="searchCriteria.sku"
          maxlength="50"
          clearable
          placeholder="sku"
        />
        <el-button type="primary" @click="searchData()">Search</el-button>
      </el-row>
      <el-row>
        <template v-if="activeState === '0'">
          <el-button
            v-preventReClick
            type="primary"
            @click="storePush()"
          >Publish</el-button>
          <el-dropdown type="primary" @command="batchEdit">
            <el-button type="primary">
              Edit<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in batchEditOptions"
                :key="index"
                :command="item.label"
              >{{ item.label }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-if="activeState === '1'">
          <el-button
            v-preventReClick
            type="primary"
            @click="copy()"
          >Copy to Drafts</el-button>
        </template>
        <template v-if="activeState === '2'">
          <el-button v-preventReClick type="primary">Republish</el-button>
        </template>
        <el-button type="primary">Delete</el-button>
      </el-row>
    </div>
    <el-table :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" :selectable="checkSelect" width="55" />
      <el-table-column label="Image" width="100">
        <template slot-scope="scope">
          <el-image
            class="productImg"
            lazy
            :src="imgPrefix + scope.row.images + imgSuffix"
            @click="toProview(imgPrefix + scope.row.images)"
          >
            <div slot="placeholder" class="image-slot">
              <i class="el-icon-loading" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="Title" />
      <el-table-column prop="sku" label="Sku" />
      <el-table-column label="Status">
        <template slot-scope="scope">
          <template v-if="activeState === '0'">
            <el-tag
              v-if="scope.row.isInvalid === 1"
              type="danger"
            >Invalid</el-tag>
            <el-tag
              v-if="scope.row.isEditStatus === 1"
              type="danger"
            >Editing</el-tag>
            <template
              v-if="scope.row.isInvalid === 0 && scope.row.isEditStatus === 0"
            >
              <el-tag
                v-if="scope.row.status === 0"
                type="danger"
              >Please edit</el-tag>
              <el-tag
                v-if="scope.row.status === 1"
                type="primary"
              >Can be released</el-tag>
            </template>
          </template>
          <el-tag v-if="activeState === '1'" type="success">successed</el-tag>
          <el-tag v-if="activeState === '2'" type="danger">filed</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="Create Time" />
      <el-table-column label="Operation" width="130">
        <template slot-scope="scope">
          <template
            v-if="
              activeState !== '1' &&
                scope.row.isInvalid === 0 &&
                scope.row.isEditStatus === 0
            "
          >
            <el-button
              v-if="scope.row.status === 1"
              v-preventReClick
              type="text"
              @click="storePush(scope.row.productId)"
            >Publish</el-button>
            <el-button
              type="text"
              @click="goDetail(scope.row.productId, scope.row.storeId)"
            >Edit</el-button>
          </template>
          <el-row>
            <el-button
              v-if="
                activeState === '1' &&
                  scope.row.isEditStatus === 0 &&
                  scope.row.isInvalid === 0
              "
              v-preventReClick
              type="text"
              @click="copy(scope.row.id, scope.row.productId)"
            >Cope</el-button>
            <el-button
              type="text"
              @click="deleteItem(scope.row.id)"
            >Delete</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      title="Batch Edit"
      :visible.sync="batchVisible"
      width="400px"
      @close="closeBatchDialog('batchForm')"
    >
      <el-form ref="batchForm" :rules="rules" :model="batchForm">
        <el-form-item
          v-if="editingField === 'Store'"
          prop="storeId"
          label="Store"
          label-width="100px"
        >
          <el-select v-model="batchForm.storeId">
            <el-option
              v-for="(item, index) in storeOptions"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="editingField === 'SKU'"
          prop="sku"
          label="SKU"
          label-width="100px"
        >
          <el-input v-model="batchForm.sku" placeholder="SKU" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeBatchDialog('batchForm')">Cancel</el-button>
        <el-button
          type="primary"
          @click="batchSubmit('batchForm')"
        >Confirm</el-button>
      </div>
    </el-dialog>

    <el-dialog title="Select Store" :visible.sync="visible" width="400px">
      <el-form>
        <el-form-item label="Store" label-width="100px">
          <el-select v-model="selectedStore">
            <el-option
              v-for="(item, index) in storeOptions"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">Cancel</el-button>
        <el-button
          type="primary"
          :disabled="!selectedStore"
          @click="claimItem"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { authorizedList } from '@/api/authorized';
import { collectPage, claim, collectDelete, copy } from '@/api/product';
import { storePush } from '@/api/common';
import TopSteps from './topSteps';
import { postResult } from '@/utils/dataFormat';
import { validateSelect, checkHalf } from '@/utils/validate';
export default {
  components: {
    TopSteps
  },
  props: {
    pageName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      activeState: '0',
      stateSteps: [
        { name: 'Drafts', pathName: '0' },
        { name: 'Success', pathName: '1' },
        { name: 'Failed', pathName: '2' }
      ],
      searchCriteria: {},
      storeOptions: [],
      tableData: [],
      multipleSelection: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      visible: false,
      selectedStore: null,
      batchEditOptions: [
        { label: 'Store', value: 0 },
        { label: 'SKU', value: 1 },
        { label: 'SEO', value: 2 }
      ],
      batchVisible: false,
      batchForm: {},
      rules: {
        storeId: [validateSelect()],
        sku: [{ required: true, validator: checkHalf, trigger: 'blur' }]
      },
      editingField: null,
      editingIds: []
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  mounted() {
    this.init();
    this.authorizedList();
  },
  methods: {
    init() {
      collectPage({
        ...this.searchCriteria,
        type: 'GATHER',
        state: ~~this.activeState,
        storeType: this.pageName === 'SHOPIFY' ? 1 : 2,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }).then((res) => {
        this.tableData = res.data.data;
        this.total = res.data.totalCount;
      });
    },
    searchData() {
      this.currentPage = 1;
      this.init();
    },
    changeState(val) {
      this.activeState = val;
      this.init();
    },
    authorizedList() {
      authorizedList({
        storeType: this.pageName
      }).then((res) => {
        this.storeOptions = res.data;
      });
    },
    batchEdit(command) {
      // 批量编辑
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('Please select at least one option');
      } else {
        this.editingIds = this.multipleSelection.map(
          (item) => item.productTemplateId
        );
      }
      this.editingField = command;
      this.batchVisible = true;
    },
    closeBatchDialog(form) {
      this.$refs[form].clearValidate();
      this.batchForm = {};
      this.editingIds = [];
      this.batchVisible = false;
    },
    batchSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          // 待对接
        } else {
          // 待对接
        }
      });
    },
    storePush(id) {
      var ids = [];
      if (id) {
        ids.push(id);
      } else {
        if (this.multipleSelection.length === 0) {
          return this.$message.warning('Please select at least one option');
        } else {
          ids = this.multipleSelection.map((item) => item.productId);
        }
      }
      storePush({ productIds: ids }).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    goDetail(productId, storeId) {
      let name = '';
      if (this.pageName === 'SHOPIFY') {
        name = 'sGatherEdit';
      } else if (this.pageName === 'WOOCOMMERCE') {
        name = 'wGatherEdit';
      }
      this.$router.push({
        name,
        params: {
          productId,
          storeId: storeId === 0 ? null : storeId
        }
      });
    },
    claimItem() {
      // 单个发布
      claim({
        ids: [this.templateId],
        storeIds: [this.selectedStore]
      }).then((res) => {
        postResult(res, this.$message, this.init());
        if (res.code === 200) {
          this.visible = false;
        }
      });
    },
    claim(command) {
      // 批量发布
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('Please select at least one option');
      } else {
        var ids = this.multipleSelection.map((item) => item.productTemplateId);
      }
      claim({
        ids,
        storeIds: [command]
      }).then((res) => {
        postResult(res, this.$message, this.init());
      });
    },
    deleteItem(id) {
      this.$confirm(
        'This action will permanently delete this product. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Yes',
          cancelButtonText: 'No',
          type: 'warning'
        }
      ).then(() => {
        collectDelete(id).then((res) => {
          postResult(res, this.$message, this.init);
        });
      });
    },
    copy(id, productId) {
      const params = {
        productCollectIds: []
      };
      if (id) {
        // 单个
        const paramItem = `${productId}_${id}`;
        params['productCollectIds'].push(paramItem);
      } else {
        // 批量
        if (this.multipleSelection.length === 0) {
          return this.$message.warning('Please select at least one');
        }
        this.multipleSelection.forEach((item) => {
          params['productCollectIds'].push(`${item.productId}_${item.id}`);
        });
      }
      copy(params).then((res) => {
        postResult(res, this.$message);
      });
    },
    checkSelect(row) {
      return row.isInvalid === 0 && row.isEditStatus === 0 && row.status !== 0;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped></style>
